package zy.ejb;

import java.util.Date;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.ejb.Init;
import javax.ejb.Local;
import javax.ejb.PostActivate;
import javax.ejb.PrePassivate;
import javax.ejb.Remote;
import javax.ejb.Remove;
import javax.ejb.SessionContext;
import javax.ejb.Stateless;
import javax.ejb.Timeout;
import javax.ejb.Timer;
import javax.interceptor.Interceptors;

/**
 * Session Bean implementation class Hello
 */
@Stateless
@Remote({ HelloRemote.class })
@Local({ HelloLocal.class })
@Interceptors({ HelloInterceptor.class })
//@EJB(name="Hello",beanInterface=HelloRemote.class)
public class Hello implements HelloRemote, HelloLocal {

	/**
	 * Default constructor.
	 */
	public Hello() {
		System.out.println("构造函数入口");
	}

	@Override
	public String sayHello_local(String msg) {
		return "HELLO LOCAL " + msg;
	}

	@Override
	public String sayHello_remote(String msg) {
		System.out.println("进入sayHello_remote()入口");
		return "HELLO REMOTE " + msg;
	}

	// 有状态bean初始化
	@Init
	public void initialize() {
		System.out.println("initialize()方法被调用");
	}

	// 构造函数之后
	@PostConstruct
	public void Construct() {
		System.out.println("构函数()方法被调用");
	}

	// 销毁bean前入口
	@PreDestroy
	public void exit() {
		System.out.println("exit()方法被调用");
	}

	// 有状态bean钝化前入口
	@PrePassivate
	public void serialize() {
		System.out.println("serialize()方法被调用");
	}

	// 有状态bean再次使用
	@PostActivate
	public void activate() {
		System.out.println("activate()方法被调用");
	}

	@Remove
	public void stopSession() {
		System.out.println("stopSession()方法被调用");
		// 调用该方法以通知容器，移除该bean实例、终止会话。方法体可以是空的。
	}

	private int count = 1;
	private @Resource SessionContext ctx;

	@Override
	public void scheduleTimer(long milliseconds) {
		ctx.getTimerService().createTimer(
				new Date(new Date().getTime() + milliseconds), milliseconds,
				new java.sql.Timestamp(System.currentTimeMillis()));
	}

	@Timeout
	public void timeoutHandler(Timer timer) {
		// System.out.println("---------------------");
		System.out.println("定时器事件发生,传进的参数为: " + timer.getInfo() + ",发生次数="
				+ count);
		// System.out.println("---------------------");
		if (count >= 5) {
			timer.cancel();// 如果定时器触发5次，便终止定时器
		}
		count++;
	}

}
